package com.cloud.sample.stomp;

import com.cloud.common.bean.SessionInfo;
import com.cloud.common.context.SessionContext;
import com.cloud.common.support.SessionCache;
import com.cloud.common.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
public class AuthInterceptor implements HandshakeInterceptor {
    @Autowired
    private SessionCache sessionCache;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        ServletServerHttpRequest httpRequest = (ServletServerHttpRequest) request;
        String token = httpRequest.getServletRequest().getParameter(SessionContext.TOKEN);
        TokenUtils.AppUser appUser = TokenUtils.parse(token);
        if (appUser == null) {
            return true;
        }
        SessionInfo sessionInfo = sessionCache.get(appUser.getAppName(), appUser.getUserId());
        if (sessionInfo == null || !sessionInfo.getSecret().equals(TokenUtils.getSecret(token))) {
            return false;
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
    }
}
